<template>
    <view class="content">
        <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft" id="navBarS">
        </van-nav-bar>

        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage" show-scrollbar="false">
            <view class="scroll_wrapper">
                <view class="moneyBg">
                    <view class="text">{{ navBarTitle }}</view>
                </view>

                <view class="serviceStatus">
                    <view class="serviceStatusSteps">
                        <!-- <van-steps :steps="steps" :active="active" active-color="#FF6203" direction="vertical"/> -->

                        <view class="service-timeline" style="margin-top: 30rpx;">
                            <view v-for="(item, index) in steps" :key="index"
                                :class="['timeline-item',index === (steps.length - 1)? 'last-item' : '']">
                                <view :class="[ index === 0 ? 'timeline-dot-active' : 'timeline-dot']"></view>
                                <view
                                    :class="['timeline-line',index === (steps.length - 1)? 'last-item-timeline-line' : '',index===0?'timeline-line-active':'']"
                                    :style="{ height: timelineLinesHeight[index]  }"></view>
                                <view class="timeline-content" :id="'timeline_content'+index">
                                    <h3 :class="['timeline-text',index===0?'timeline-text-active':'']">{{ item.detailDesc}}</h3>
                                    <p class="timeline-desc">{{ item.operationUser }}</p>
                                    <!-- <rich-text :nodes="item.remarkNodes" class="timeline-desc" @itemclick="(e) => {
                                        const phone = e.detail.dataset.phone;
                                        phone && handlePhoneCall(phone);
                                    }" /> -->
                                    <!-- <view class="remark-container timeline-desc">
                                        <block v-for="(i,j) in item.remarkNodes[0].children " :key="j">
                                            <view v-if="i.name === 'text'" :class="i.attrs.class">
                                                {{ i.children[0].text }}</view>
                                            <view v-else @tap="handlePhone"
                                                :data-phone="i.attrs['data-phone']" :class="i.attrs.class">
                                                {{ i.children[0].text }}</view>
                                        </block>
                                    </view> -->
                                    <p class="timeline-time">{{ item.operationTime }}</p>
                                </view>
                            </view>
                        </view>

                    </view>
                </view>

            </view>
        </scroll-view>
    </view>
</template>

<script>
import { getSelfPickupExpressDetailApi } from '@/api/merchant'
export default {
    components: { },
    data() {
        return {
            navBarTitle: '服务流程',
            scrolling:false,
            
            active:0,
            activeIndex:0,
            steps: [
                {
                    text: '已预约',
                    remark:'服务人员王涛（15632642154）已服务',
                    time: '2021-12-21 14:30',
                },
                {
                    text: '已派单',
                    remark: '社区家政服务公司（0359-2365235）派单给服务人员王涛（15632642154）',
                    time: '2021-12-21 14:30'
                },
                {
                    text: '已服务',
                    remark: '服务人员王涛（15632642154）已服务',
                    time: '2021-12-21 14:30'
                },
                // {
                //     text: '待评价',
                //     // inactiveIcon: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/noCheck0113.png',
                //     activeIcon: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png'
                // }
            ],
            
            params:undefined, //接受从路由传过来的参数
            activeIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png',  
            inactiveIcon: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/noCheck0113.png', 
            timeline_line:'',
            timelineLinesHeight: [],
            serviceStatus:undefined,
            orderId:undefined,
            statusMap:{
                'order':'待服务',
                'cancel':'已取消',
                'wait_replay':'待评价',
                'replay':'已完成'
            }
        }
    },
    onLoad(data) {

        if(data){
            console.log(data,'data')
            // this.params=JSON.parse(decodeURIComponent(data.params))
            // this.serviceStatus = this.params.serviceStatus
            // // this.active=Number(this.params.actStatus)
            // this.activeIndex=Number(this.params.activeIndex)
            this.orderId=data.orderId
            this.getSelfPickupExpressDetail(this.orderId)
            // if(this.params.serviceStatus==='ordered'){
            //     this.navBarTitle='待服务'
            //     if(this.params.clickType==='button'){
            //         this.showCancel=true
            //     }
            // }else if(this.params.serviceStatus== 'canceled') {  //已服务 待评价  
            //     this.navBarTitle='已取消'
            // }else if(this.params.serviceStatus== 'wait_replay') {  //已服务 待评价  
            //     this.navBarTitle='待评价'
            // }else if(this.params.serviceStatus==='replay'){ 
            //      this.navBarTitle='已完成'
            //      if(this.params.clickType==='button'){
            //         this.show=true
            //     }
            // }
            
        }
    },
    onReady () {
        if(this.steps.length>0){
            // this.steps = this.steps.reverse(); // 反转数组，确保最新的在最前面
            const updatePromises = [];
            this.steps.forEach((item, index) => {
                updatePromises.push(this.setTimelineLineHeight(index));
            })
            Promise.all(updatePromises).then(() => {  // 在这里可以添加一些依赖于高度都更新完成后的逻辑，比如检查视图是否正确显示高度等
                console.log('所有竖线高度更新完成',updatePromises);
            });
            console.log(this.steps,'steps')
        }
    },
    methods: {
        // 滑动
        scrollPage(e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft () {
            uni.navigateBack()
        },
        // 拨打电话
        // 处理电话号码的点击事件
        // handlePhoneCall(number) {
        //     uni.makePhoneCall({
        //         phoneNumber: number
        //     });
        // },
        handlePhone(e) {
            console.log(e.currentTarget.dataset.phone,e,'e')
            const phoneNumber = e.currentTarget.dataset.phone;
            wx.makePhoneCall({
                phoneNumber,
                success() {
                    console.log('拨打电话成功');
                },
                fail(err) {
                    console.error('拨打电话失败', err);
                }
            });
        },
        // 流程图左侧的竖线
        getItemHeight(index) {
            return new Promise((resolve) => {
                const query = wx.createSelectorQuery().in(this);
                query.select(`#timeline_content${index}`).boundingClientRect((rect) => {
                    console.log(rect,'rect')
                    const contentHeight = rect.height;
                    resolve(rect ? contentHeight + 30 : 0); 
                }).exec();
            });
        },
        // async setTimelineLineHeight(index) {
        //     const height = await this.getItemHeight(index);
        //     console.log(height,'kkkll')
        //     this.timelineLinesHeight[index]= height + 'px'
        //     console.log(this.timelineLinesHeight)
        //     this.$forceUpdate()
        //     // return new Promise((resolve) => {
        //     //     // 可以简单地通过 setTimeout 模拟等待视图更新完成，实际可能需要更精准的判断机制
        //     //     setTimeout(() => {
        //     //         resolve();
        //     //     }, 0);
        //     // });
        // },
        // 设置时间线高度
        async setTimelineLineHeight(index) {
            try {
                const height = await this.getItemHeight(index);
                this.$set(this.timelineLinesHeight, index, `${height}px`);
            } catch (e) {
                console.error('获取高度失败:', e);
            }
        },
        async getSelfPickupExpressDetail(orderId){
            getSelfPickupExpressDetailApi(orderId).then(async res=>{
                console.log(res,'res')
                if(res.code===200){
                    // this.steps=res.data
                    this.steps = [...res.data].reverse()
                    // this.steps = res.data.map(item => ({
                    //     ...item,
                    //     // // 使用正则表达式匹配<label>标签中的数字，转换为可点击的富文本节点
                    //     // remarkNodes: [{
                    //     //     name: 'span',
                    //     //     attrs: { class: 'phone-container' },
                    //     //     children: item.remark.split(/<label>|<\/label>/).map(text => {
                    //     //         const isPhone = /^\d+$/.test(text);
                    //     //         return {
                    //     //             name: isPhone ? 'span' : 'text',
                    //     //             attrs: {
                    //     //                 class: isPhone ? 'phone-number' : '',
                    //     //                 'data-phone': isPhone ? text : '',
                    //     //                 onClick: isPhone ? 'handlePhone' : ''
                    //     //             },
                    //     //             children: [{ type: 'text', text }]
                    //     //         };
                    //     //     })
                    //     // }]
                    // }));
                    console.log(this.steps, 'this.steps')
                    await this.$nextTick();
                    const promises = this.steps.map((_, index) =>
                        this.setTimelineLineHeight(index)
                    );
                    await Promise.all(promises);
                }
            })
        }

    }
}
</script>

<style lang="scss" scoped>
.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    height:100vh;
    overflow:hidden;
    box-sizing: border-box;
}
.scroll-content {
    flex: 1;
    height: 1px;
}
.scroll_wrapper{
    padding-bottom: calc(144rpx + env(safe-area-inset-bottom));
}
.moneyBg{
    margin-top: 17px;
    margin-left: 24px;
    margin-right: 24px;
    display: flex;
    align-items: center;
}
.text{
    font-size: 30px;
    text-align: center;
    color: #111111;
    line-height: 30px;
}
.money{
    font-size: 20px;
    color: #111111;
    text-align: center;
    line-height: 20px;
    margin-left:19px;
}

.serviceStatus {
padding-top: 55rpx;
margin: 0rpx 48rpx;
    .serviceStatusTop {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .serviceStatusTitle {
            font-size: 36rpx;
            line-height: 36rpx;
            text-align: left;
            color: #111111;
        }

        .act_more {
            line-height: 24rpx;
            vertical-align: middle;
            height: 24rpx;
            font-size: 24rpx;
            text-align: right;
            color: #666666;

            .act_t {
                color: #888888;
                font-size: 24rpx;
                line-height: 24rpx;
                margin-right: 17rpx;
            }

            .act_Im {
                vertical-align: -2rpx;
            }
        }
    }
    .serviceStatusSteps {
        // padding-top: 60rpx;
        padding-bottom: 77rpx;
    }
}


::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep #navBarS .van-icon {
    color: #242629 !important;
}
::v-deep .van-cell{
    padding-left: 0px !important;
    border-bottom: 1px solid #f9f9f9;
}


 .t16{
    margin-top: 16px;
 }


 .service-timeline {
//   margin-top: 40rpx;
  padding-left: 30rpx;
}

.timeline-item {
  position: relative;
  padding-bottom: 78rpx;
//   min-height: 120rpx; /* 最小高度防止空状态 */
}
// 左侧的点
.timeline-dot {
  position: absolute;
  left: -9rpx;
  top: 7rpx;
  width: 18rpx;
  height: 18rpx;
  border-radius: 50%;
  background-color: #d4d4d4;
}
// 左侧第一个点
.timeline-dot-active{
    position: absolute;
    left: -18rpx;
    top: 0;
    width: 36rpx;
    height: 36rpx;
    line-height: 36rpx;
    background: url('https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/processDot.png') no-repeat;
    background-size: 100%;
}
// 左侧active点
.active .timeline-dot {
  background-color: #ff6023;
}

// 左侧的竖线
.timeline-line {
  position: absolute;
  left:0px;
  top: 24rpx;
  bottom: 0;
  width: 2rpx;
  background-color: #ccc;
}
.timeline-line-active{
    background-color: #ff6023;
}

.timeline-content {
  margin-left: 30rpx;
}
.timeline-text{
    font-size: 28rpx;
    line-height: 28rpx;
    font-weight: bolder;
}
.timeline-text-active{
    color: #ff6023;
}
.timeline-desc{
    font-size: 24rpx;
    color: #111111;
    margin-top: 28rpx;
}
.timeline-time {
  color: #888888;
  font-size: 24rpx;
  line-height: 24rpx;
  margin-top: 28rpx;
}
.last-item.timeline-line {
  display: none;
}
.last-item-timeline-line{
    height: 0rpx;
    display: none !important;
}
::v-deep .desc-class{
    font-size: 24rpx !important;
    line-height: 24rpx;
    text-align: left;
    color: #111111 !important;
}

// 有电话的部分
.remark-container {
    display: flex;
    align-items: center;
}
.phone-number {
    color: #1989fa;
    position: relative;
    padding: 0 4rpx;
    
    &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: -4rpx;
        border-bottom: 1rpx solid #1989fa;
    }
}
</style>
